package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NcUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.NcOuputCfMapper;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 菜房出库 服务层实现
 *
 * @author ruoyi
 * @date 2019-08-30
 */
@Service
public class NcOuputCfServiceImpl implements INcOuputCfService {
    @Autowired
    private NcOuputCfMapper ncOuputCfMapper;

    @Autowired
    private INcOrderService orderService;

    @Autowired
    private INcCaiService ncCaiService;


    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private INcOrderCfService orderCfService;

    /**
     * 查询菜房出库信息
     *
     * @param outputId 菜房出库ID
     * @return 菜房出库信息
     */
    @Override
    public NcOuputCf selectNcOuputCfById(Integer outputId) {
        return ncOuputCfMapper.selectNcOuputCfById(outputId);
    }

    /**
     * 查询菜房出库列表
     *
     * @param ncOuputCf 菜房出库信息
     * @return 菜房出库集合
     */
    @Override
    public List<NcOuputCf> selectNcOuputCfList(NcOuputCf ncOuputCf) {
        return ncOuputCfMapper.selectNcOuputCfList(ncOuputCf);
    }

    /**
     * 新增菜房出库
     *
     * @param ncOuputCf 菜房出库信息
     * @return 结果
     */
    @Override
    public int insertNcOuputCf(NcOuputCf ncOuputCf) {
        return ncOuputCfMapper.insertNcOuputCf(ncOuputCf);
    }

    /**
     * 修改菜房出库
     *
     * @param ncOuputCf 菜房出库信息
     * @return 结果
     */
    @Override
    public int updateNcOuputCf(NcOuputCf ncOuputCf) {
        return ncOuputCfMapper.updateNcOuputCf(ncOuputCf);
    }

    /**
     * 删除菜房出库对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteNcOuputCfByIds(String ids) {
        return ncOuputCfMapper.deleteNcOuputCfByIds(Convert.toStrArray(ids));
    }

    @Override
    public int createOutputOrderByIds(String ids, SysUser user,Integer caifangType) {
        NcOrder o = new NcOrder();

        if (StringUtils.isNotEmpty(ids)) {
            /*创建菜房出库单*/
            o.setOrderCode(NcUtils.getOrderCode());
            if(caifangType != null && caifangType == 2){
                o.setOrderType(Constants.ORDER_OUTPUT3);
            }
            else{
                o.setOrderType(Constants.ORDER_OUTPUT1);
            }
            o.setOrderTime(new Date());
            o.setCreateTime(new Date());
            o.setCreateBy(user.getUserName());
            orderService.insertNcOrder(o);

            System.out.println("----------orderId-------:" + o.getOrderId());
            String[] idArr = Convert.toStrArray(ids);
            for (String id : idArr) {
                NcOuputCf ouputCf = selectNcOuputCfById(Integer.parseInt(id));
                ouputCf.setOrderId(o.getOrderId());
                ouputCf.setStatus("2");//已生成订单
                updateNcOuputCf(ouputCf);
            }

            return 1;
        } else {
            return 0;
        }

    }

    @Override
    public Map getOutputCount(NcOrderCf order) {
        List<Map> maps = selectSumByStatus(order);
        Double total = 0.;
        Double cf1 = 0.;
        Double cf2 = 0.;
        for (Map m : maps) {
            if ("1".equals("" + m.get("cforderFor"))) {
                cf1 = NcUtils.getCountD(m, "amount");
                total += NcUtils.getCountD(m, "amount");
            }
            if ("2".equals("" + m.get("cforderFor"))) {
                cf2 = NcUtils.getCountD(m, "amount");
                total += NcUtils.getCountD(m, "amount");
            }

        }
        Map map = new HashMap();
        map.put("total", total);
        map.put("cf1", cf1);
        map.put("cf2", cf2);
        return map;
    }

    @Override
    public List<NcCai> getBigCaiClass(NcOrderCf order) {
        //1、计算菜房订单出库数量
        NcCai cai = new NcCai();
        cai.setAncestors("0");
        cai.setParentId(new Long(0));
        List<NcCai> result = ncCaiService.selectBigClass(cai);
        //过滤
        for (NcCai c : result) {
            //遍历取计划数量数量
            order.getParams().put("ancestors", c.getCaiId());
            c.setPlanCounts(getOutputCount(order));
        }
        //计算占比
        Integer total = 0;
        Integer cf1 = 0;
        Integer cf2 = 0;
        for (NcCai c : result) {
            Map counts = c.getPlanCounts();
            total += NcUtils.getCount(counts, "total");
            cf1 += NcUtils.getCount(counts, "cf1");
            cf2 += NcUtils.getCount(counts, "cf2");

        }

        for (NcCai c : result) {
            Map counts = c.getPlanCounts();
            counts.put("total_rate", NcUtils.getRate(total, counts, "total"));
            counts.put("cf1_rate", NcUtils.getRate(cf1, counts, "cf1"));
            counts.put("cf2_rate", NcUtils.getRate(cf2, counts, "cf2"));
        }
        return result;
    }

    public List<Map> selectSumByStatus(NcOrderCf cf) {
        return ncOuputCfMapper.selectSumByStatus(cf);
    }

    /*设置不同出库类型的数量*/
    @Override
    public void setOutputTypes(ModelMap mmap, NcOrderCf order) {
        List<SysDictData> cforderTypes = dictDataService.selectDictDataByType("cforderType");
        List<Double> all = new ArrayList<>();
        List<Double> cf1 = new ArrayList<>();
        List<Double> cf2 = new ArrayList<>();
        //菜房1
        Double total = 0.;
        for (SysDictData d : cforderTypes) {
            order.setCforderFor(1);
            order.getParams().put("outputType", d.getDictValue());
            Double sum = selectSum(order);
            cf1.add(sum);
            total += sum;
        }
        cf1.add(0, total);

        //菜房2
        total = 0.;
        for (SysDictData d : cforderTypes) {
            order.setCforderFor(2);
            order.getParams().put("outputType", d.getDictValue());
            Double sum = selectSum(order);
            cf2.add(sum);
            total += sum;
        }
        cf2.add(0, total);


        //设置全部的
        for (int i = 0; i < cforderTypes.size() + 1; i++) {
            Double a = cf1.get(i) + cf2.get(i);
            all.add(a);
        }


        List<Map> all_m = new ArrayList<>();
        List<Map> cf1_m = new ArrayList<>();
        List<Map> cf2_m = new ArrayList<>();
        /*做成Map*/
        for (int i = 0; i < cforderTypes.size(); i++) {
            SysDictData dict = cforderTypes.get(i);
            all_m.add(addMap(dict.getDictLabel(), all.get(i + 1)));
            cf1_m.add(addMap(dict.getDictLabel(), cf1.get(i + 1)));
            cf2_m.add(addMap(dict.getDictLabel(), cf2.get(i + 1)));
        }

        all_m.add(0, addMap("合计产量", all.get(0)));
        cf1_m.add(0, addMap("合计产量", cf1.get(0)));
        cf2_m.add(0, addMap("合计产量", cf2.get(0)));

        mmap.put("all", all_m);
        mmap.put("cf1", cf1_m);
        mmap.put("cf2", cf2_m);

    }

    @Override
    public void innoInfo(String beginTime, String endTime, ModelMap mmap, String dataType, String output) {
        Map cfMap = new HashMap();
        cfMap.put("name","蔬菜总产量");
        Double totalCf = ncOuputCfMapper.selectCfByMonthRange(beginTime,endTime,output);
        // 趋势和日均
        int totalDays = findDays(dataType);
        if("year".equals(dataType)){  // 年趋势
            List<String> monthList = DateUtils.getEachMonthList();
            List<Double> totalList = new ArrayList<>();
            for(String s : monthList){
                Double total = ncOuputCfMapper.selectCfTotalByMonth(s,output);
                totalList.add(total == null ? 0 : total);
            }
            mmap.put("yDateCf",totalList);
        }else if("month".equals(dataType)){  // 月趋势
            List<String> daysList = DateUtils.getEachDaysList();
            List<Double> totalList = new ArrayList<>();
            for(String s : daysList){
                Double total = ncOuputCfMapper.selectCfTotalByDays(s,output);
                totalList.add(total == null ? 0 : total);
            }
            mmap.put("yDateCf",totalList);

        }else if("day".equals(dataType)){   // 日趋势
            List<String> daysList = DateUtils.getBeforeSevenDay();
            List<Double> totalList = new ArrayList<>();
            for(String s : daysList){
                Double total = ncOuputCfMapper.selectCfTotalByDays(s,output);
                totalList.add(total == null ? 0 : total);
            }
            mmap.put("yDateCf",totalList);
        }else if("search".equals(dataType)){   // 时间段查询
            List<String> daysList = DateUtils.getBetweenTime(beginTime,endTime);
            totalDays = daysList.size();
            List<Double> totalList = new ArrayList<>();
            for(String s : daysList){
                Double total = ncOuputCfMapper.selectCfTotalByDays(s,output);
                totalList.add(total == null ? 0 : total);
            }
            mmap.put("yDateCf",totalList);
        }else{
        }
        cfMap.put("amount",totalCf == null ? 0 : totalCf);
        cfMap.put("dayAmount",totalCf == null ? 0 : division(totalCf ,totalDays));
        mmap.put("cf",cfMap);
    }

    private Object division(Double a, int b) {
        String result = "";
        double num =(double)a/b;
        DecimalFormat df = new DecimalFormat("0.0");
        result = df.format(num);
        return result;
    }

    private int findDays(String dataType) {
        Date yearsDate = DateUtils.getBeginDayOfYear();
        Date monthDate = DateUtils.getBeginDayOfMonth();
        Date nowDate = DateUtils.getNowDate();
        if("year".equals(dataType)){
            return DateUtils.getDiffDays(yearsDate,nowDate);
        }else if("month".equals(dataType)){
            return DateUtils.getDiffDays(monthDate,nowDate);
        }else{
            return 1;
        }
    }


    @Override
    public BigDecimal queryOutAmoutByPlanId(Long planId) {

        return ncOuputCfMapper.queryOutAmoutByPlanId(planId);
    }

    @Override
    public void innoInfoType(String beginTime, String endTime, ModelMap mmap, String type) {

    }

    @Override
    public Double selectSum(NcOrderCf order) {
        Double integer = ncOuputCfMapper.selectSum(order);
        if (integer == null) {
            return 0.;
        }

        return integer;
    }

    private Map addMap(String key, Double value) {
        Map m = new HashMap();
        m.put("name", key);
        m.put("value", value);
        return m;
    }

    @Override
    public List<Map> selectCountByTime(Integer outputType, Integer dataSpan, String beginTime, String endTime, int cf) {
        Date s = null;
        Date e = null;
        Map se = orderCfService.calTimeSpan(s, e, beginTime, endTime, dataSpan);
        s = (Date) se.get("s");
        e = (Date) se.get("e");

        //查找出库数量
        return getSumByDate(dataSpan, s, e, outputType, cf);
    }

    @Override
    public double selectCFoutPutScreen(NcOuputCf ncOuputCf) {
        return ncOuputCfMapper.selectCFoutPutScreen(ncOuputCf);
    }

    @Override
    public List<NcOuputCf> avgCFoutPutScreen(NcOuputCf ncOuputCf) {

      return ncOuputCfMapper.avgCFoutPutScreen(ncOuputCf);
    }

    private List<Map> getSumByDate(Integer dataSpan, Date s, Date e, Integer outputType, int cf) {
        List<Map> result = new ArrayList<>();
        if (dataSpan == 1) {
            while (e.getTime() >= s.getTime()) {
                String date = DateUtils.parseDateToStr("yyyy", s);

                Map m = new HashMap();
                m.put("x", date);
                m.put("count", getSumByDate(date, dataSpan, outputType, cf));
                result.add(m);

                s = DateUtils.addYears(s, 1);
            }
        } else if (dataSpan == 2) {
            while (e.getTime() >= s.getTime()) {
                String date = DateUtils.parseDateToStr("yyyy-MM", s);
                Map m = new HashMap();
                m.put("x", date);
                m.put("count", getSumByDate(date, dataSpan, outputType, cf));
                result.add(m);
                s = DateUtils.addMonths(s, 1);
            }
        } else if (dataSpan == 3) {
            while (e.getTime() >= s.getTime()) {
                String date = DateUtils.parseDateToStr("yyyy-MM-dd", s);
                Map m = new HashMap();
                m.put("x", date);
                m.put("count", getSumByDate(date, dataSpan, outputType, cf));
                result.add(m);
                s = DateUtils.addDays(s, 1);
            }
        }
        return result;
    }

    private Double getSumByDate(String dateSpan, Integer dataSpan, Integer outputType, int cf) {
        NcOrderCf order = new NcOrderCf();
        if (dataSpan == null || dataSpan == 2) {
            order.getParams().put("dateSpanMonth", dateSpan);
        } else if (dataSpan == 1) {
            order.getParams().put("dateSpanYear", dateSpan);
        } else if (dataSpan == 3) {
            order.getParams().put("dateSpanDay", dateSpan);
        }
        order.setStatus("2");//已生成单子
        if (outputType != null && outputType > 0) {
            order.getParams().put("outputType", outputType);
        }
        order.setCforderFor(cf);

        return ncOuputCfMapper.selectSum(order);
    }
    //前端内部消息
    public List<Map> selectInfoByTime(Integer spanType, String beginTime, String endTime,String outputType) {
        Date s = null;
        Date e = null;
        Map se = orderCfService.calTimeSpan(s, e, beginTime, endTime, spanType);
        s = (Date) se.get("s");
        e = (Date) se.get("e");

        return getSumInfoByDate(spanType, s, e,outputType);
    }
    //前端内部消息
    private List<Map> getSumInfoByDate(Integer spanType, Date s, Date e,String outputType) {
        List<Map> result = new ArrayList<>();
        if (spanType == 1) {
            while (e.getTime() >= s.getTime()) {
                String dateSpan = DateUtils.parseDateToStr("yyyy", s);

                Map m = new HashMap();
                m.put("x", dateSpan);
                m.put("cfCount", getByDate(dateSpan, spanType,outputType));
                result.add(m);

                s = DateUtils.addYears(s, 1);
            }
        } else if (spanType == 2) {
            while (e.getTime() >= s.getTime()) {
                String dateSpan = DateUtils.parseDateToStr("yyyy-MM", s);
                Map m = new HashMap();
                m.put("x", dateSpan);
                m.put("cfCount", getByDate(dateSpan, spanType,outputType));
                result.add(m);
                s = DateUtils.addMonths(s, 1);
            }
        } else if (spanType == 3) {
            while (e.getTime() >= s.getTime()) {
                String dateSpan = DateUtils.parseDateToStr("yyyy-MM-dd", s);
                Map m = new HashMap();
                m.put("x", dateSpan);
                m.put("cfCount", getByDate(dateSpan, spanType,outputType));
                result.add(m);
                s = DateUtils.addDays(s, 1);
            }
        }
        return result;
    }
    //前端内部消息
    private Double getByDate(String dateSpan, Integer dataSpan,String outputType) {
        NcOuputCf cf = new NcOuputCf();
        if (dataSpan == null || dataSpan == 2) {
            cf.getParams().put("dateSpanMonth", dateSpan);
        } else if (dataSpan == 1) {
            cf.getParams().put("dateSpanYear", dateSpan);
        } else if (dataSpan == 3) {
            cf.getParams().put("dateSpanDay", dateSpan);
        }
        if(outputType != null &&  outputType.equals("all") == false){
            cf.setOutputType(Integer.valueOf(outputType));
        }

        return ncOuputCfMapper.selectCfInfo(cf);
    }



}
